package com.leyou.auth.utils;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.leyou.auth.constants.RedisConstants;
import com.leyou.auth.dto.Payload;
import com.leyou.auth.dto.UserDetails;
import com.leyou.common.exception.LyException;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;


import javax.crypto.SecretKey;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.UUID;
import java.util.concurrent.TimeUnit;


public class JwtUtils {

    /**
     * JWT解析器
     */
    private final JwtParser jwtParser;
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    /**
     * 秘钥
     */
    private final SecretKey secretKey;

    private final static ObjectMapper mapper = new ObjectMapper();

    public JwtUtils(String key) {
        // 生成秘钥
        secretKey = Keys.hmacShaKeyFor(key.getBytes(Charset.forName("UTF-8")));
        // JWT解析器
        this.jwtParser = Jwts.parserBuilder().setSigningKey(secretKey).build();
    }

    /**
     * 生成jwt，用默认的JTI
     *
     * @param userDetails 用户信息
     * @return JWT
     */
    public String createJwt(UserDetails userDetails) {
        return createJwt(userDetails, 1800);
    }

    /**
     * 生成jwt，自己指定的JTI
     *
     * @param userDetails 用户信息
     * @return JWT
     */
    public String createJwt(UserDetails userDetails, int expireSeconds) {
        try {
            // 生成token
            String user = Jwts.builder().signWith(secretKey)
                    .setId(createJti())
                    .claim("user", mapper.writeValueAsString(userDetails))
                    .setExpiration(DateTime.now().plusSeconds(expireSeconds).toDate())
                    .compact();
            // 放到缓存中
        stringRedisTemplate.opsForValue().set(RedisConstants.JTI_KEY_PREFIX + userDetails.getId(),user,expireSeconds,TimeUnit.SECONDS);
        return user;
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 解析jwt，并将用户信息转为指定的Clazz类型
     *
     * @param jwt   token
     * @return 载荷，包含JTI和用户信息
     */
    public Payload parseJwt(String jwt) {

            //验证解析jwt
            Jws<Claims> claimsJws = jwtParser.parseClaimsJws(jwt);
            Claims claims = claimsJws.getBody();
            //解析载荷数据
            Payload payload = new Payload();
            payload.setJti(claims.getId());
        UserDetails userDetails=null;
        try {
             userDetails = mapper.readValue(claims.get("user", String.class), UserDetails.class);
            payload.setUserDetail(userDetails);

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        //取出验证是否过期
        String s = stringRedisTemplate.opsForValue().get(RedisConstants.JTI_KEY_PREFIX + userDetails.getId());
        String jti = payload.getJti();
        //判断
        if (s==null){
            throw new LyException(400,"登录已过期");
        }
        if (!s.equals(jti)){
            throw new LyException(400,"用户可能在其他设备登录");
        }
        return payload;
    }

    private String createJti() {
        return StringUtils.replace(UUID.randomUUID().toString(), "-", "");
    }

    /**
     * 刷新有效期
     * @param userId 用户id
     */
    public void refreshJwt(Long userId){
        refreshJwt(userId, RedisConstants.TOKEN_EXPIRE_SECONDS);
    }
    //刷新jwt有效期
    private void refreshJwt(Long userId, int tokenExpireSeconds) {
        stringRedisTemplate.expire(RedisConstants.JTI_KEY_PREFIX+userId,tokenExpireSeconds,TimeUnit.SECONDS);
    }
}